#!/bin/bash
# for ubuntu 22.04 & 24.04
# version: 1.1
# author:https://github.com/xiecheesejohn
# 定义变量，安装前需要先修改以下变量
NGINX_VERSION=1.26.1              # nginx版本
NGINX_INSTALL_DIR=/usr/local/nginx   # 安装路径
NGINX_SRC_DIR=/usr/local/src        # nginx源代码存放位置
NGINX_URL=http://nginx.org/download  # nginx源代码下载网站




# 定义颜色函数
color() {           # 用法：color "打印的信息" 0|1 success|failure 打印行尾提示。
    local RES_COL=$(( $(tput cols) / 2 ))
    local SETCOLOR_SUCCESS="\033[1;32m"  # 绿色
    local SETCOLOR_FAILURE="\033[1;31m"  # 红色
    local SETCOLOR_WARNING="\033[1;33m"  # 黄色
    local SETCOLOR_NORMAL="\033[0m"      # 重置颜色
    printf "$1"
    printf '\033[%sG' "$RES_COL"
    printf "["

    case $2 in
        success|0)
            printf "$SETCOLOR_SUCCESS"
            printf "  OK  "
            ;;
        failure|1)
            printf "$SETCOLOR_FAILURE"
            printf "FAILED"
            ;;
        *)
            printf "$SETCOLOR_WARNING"
            printf "WARNING"
            ;;
    esac

    printf "$SETCOLOR_NORMAL"
    printf "]\n"
}

download_nginx () { # $1参数为下载url $2参数为下载目标路径
    wget $1 -P $2 &> /dev/null
}

check_src_file () {
    if [ -e ${NGINX_SRC_DIR}/nginx-${NGINX_VERSION}.tar.gz  ] || [ -e nginx-${NGINX_VERSION}.tar.gz ];then
        color "发现文件 nginx-${NGINX_VERSION}.tar.gz
nginx源代码已准备好." 0
    else
        color "\E[1;32m${NGINX_SRC_DIR} 路径下没有发现nginx，准备下载...\E[0;m" 10
        download_nginx "${NGINX_URL}/nginx-${NGINX_VERSION}.tar.gz" "${NGINX_SRC_DIR}" &> /dev/null
        if [ $? -eq 0 ];then
            color "下载成功，nginx源代码已准备好." 0
        else
            color "下载失败，请检查url或网络" 1
            exit 1
        fi
    fi
    tar -xvf "${NGINX_SRC_DIR}/nginx-${NGINX_VERSION}.tar.gz" -C "${NGINX_SRC_DIR}" &> /dev/null
    tar -xvf "nginx-${NGINX_VERSION}.tar.gz" -C "${NGINX_SRC_DIR}" &> /dev/null

}

compile_install_nginx () { 
    echo "正在通过apt源安装依赖包......"
    apt update &> /dev/null
    [ $? -ne 0 ] && { color "更新apt源失败" 1; exit 2; } 
    apt -y install gcc make  libpcre3 libpcre3-dev openssl libssl-dev zlib1g-dev libgd-dev &> /dev/null
    [ $? -ne 0 ] && { color "安装依赖包失败" 1; exit 2; } 
    color "依赖包安装完成" 0
    if id nginx &> /dev/null;then
        color "已存在nginx用户。跳过创建用户步骤" 10
    else
        useradd -M -r -s  /sbin/nologin nginx && color "已完成nginx用户创建，并注册为系统用户" 0
    fi
    echo "正在从源代码编译nginx......"
    cd "${NGINX_SRC_DIR}/nginx-${NGINX_VERSION}" ||   { color "no such directory." 1 ;exit; }
    ./configure --prefix=${NGINX_INSTALL_DIR} --user=nginx --group=nginx \
    --with-pcre --with-http_ssl_module --with-http_v2_module \
    --with-http_realip_module --with-http_addition_module --with-http_sub_module \
    --with-http_dav_module --with-http_flv_module --with-http_mp4_module \
    --with-http_gunzip_module --with-http_gzip_static_module \
    --with-http_random_index_module --with-http_secure_link_module \
    --with-http_stub_status_module --with-http_auth_request_module \
    --with-http_image_filter_module --with-http_slice_module --with-mail \
    --with-threads --with-file-aio --with-stream --with-mail_ssl_module \
    --with-stream_ssl_module &> /dev/null ||  { color "nginx 编译安装失败,退出!" 1 ;exit; }
    make &> /dev/null
    make install &> /dev/null \
    && color "nginx 编译安装成功" 0 ||  { color "nginx 编译安装失败,退出!" 1 ;exit; }
}

init_start_nginx () {
chown -R nginx:nginx "${NGINX_INSTALL_DIR}" \
&&  color "配置nginx文件权限为nginx用户所有" 0

echo "PATH=${NGINX_INSTALL_DIR}/sbin:\${PATH}" > /etc/profile.d/nginx.sh && color "完成配置nginx PATH环境变量" 0

echo "配置systemd service文件..."
cat > /etc/systemd/system/nginx.service<<EOF
[Unit]
Description=nginx - high performance web server
Documentation=https://nginx.org/en/docs/
After=network-online.target remote-fs.target nss-lookup.target
Wants=network-online.target

[Service]
Type=forking
PIDFile=${NGINX_INSTALL_DIR}/logs/nginx.pid
ExecStartPre=${NGINX_INSTALL_DIR}/sbin/nginx -t
ExecStart=${NGINX_INSTALL_DIR}/sbin/nginx  -c ${NGINX_INSTALL_DIR}/conf/nginx.conf
ExecReload=/bin/sh -c "/bin/kill -s HUP \$(/bin/cat ${NGINX_INSTALL_DIR}/logs/nginx.pid)"
ExecStop=/bin/sh -c "/bin/kill -s TERM \$(/bin/cat ${NGINX_INSTALL_DIR}/logs/nginx.pid)"
KillSignal=SIGQUIT
TimeoutStopSec=5
KillMode=process
LimitNOFILE=100000
Restart=always
[Install]
WantedBy=multi-user.target
EOF
systemctl daemon-reload &> /dev/null
systemctl start nginx &> /dev/null
[ $? -eq 0 ] && color "nginx启动成功" 0 || { color "nginx启动失败" 1;exit; }
systemctl enable nginx &> /dev/null
}

check_src_file
compile_install_nginx
init_start_nginx